package com.jbp.controller;
import java.math.BigDecimal;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.service.*;
import com.jbp.utils.PageUtils;
import com.jbp.utils.R;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 充值(WalletPay)表控制层
 * @author cc
 * @since 2020-07-02 11:45:11
 */
@Api(tags ="APP接口--充值" )
@ApiIgnore
@RestController
@RequestMapping("rest/pay")
public class WalletPayController {
    @Autowired
    private WalletPayService walletPayService;
    @Autowired
    private PropertyService propertyService;
    @Autowired
    private PayConfigService payConfigService;
    @Autowired
    private IdentifyService identifyService;
    @Autowired
    private AlipayConfigService alipayConfigService;
    @Autowired
    private WechatConfigService wechatConfigService;
    @Autowired
    private AppConfigService appConfigService;
    @Autowired
    private ApplePayGoodsService applePayGoodsService;
    /** 列表 */
    @ApiOperation(value="列表")
    @ApiResponses({
            @ApiResponse(code = 200,message = "成功",response = WalletPay.class),
            @ApiResponse(code = 201,message = "返回失败信息")
    })
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params, @RequestAttribute("userId")Integer userId){
        params.put("userId", userId);
        PageUtils page = walletPayService.queryPage(params);
        return R.ok().put("page", page);
    }
    
    /** 创建支付宝订单 */
    @ApiOperation(value="创建订单")
    @PostMapping("/createOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "money",value = "金额",paramType = "body")
    })
    public R createOrder(@RequestBody WalletPay walletPay, @RequestAttribute("userId")Integer userId){
        if (walletPay.getPayType()==null) {
            return R.error("请选择充值类型");
        }
        String payType = walletPay.getPayType();
        if ("alipay".equalsIgnoreCase(payType) && !"1".equals(propertyService.getV("alipay_on"))) {
            return R.error("敬请期待");
        }
        if ("wechat".equalsIgnoreCase(payType) && !"1".equals(propertyService.getV("wechat_on"))) {
            return R.error("敬请期待");
        }
        if (walletPay.getMoney()==null) {
            return R.error("金额错误");
        }
        if (walletPay.getMoney().compareTo(BigDecimal.valueOf(1000000))>0) {
            return R.error("金额过大");
        }
        if (new BigDecimal(walletPay.getMoney().intValue()).compareTo(walletPay.getMoney()) != 0){
            return R.error("充值金额必须是整数");
        }
        int money = walletPay.getMoney().intValue();
        if (money<1) {
            return R.error("金额错误");
        }
        Integer xinZuan = null;
        PayConfig payConfig = payConfigService.getOne(new QueryWrapper<PayConfig>().eq("money", money));
        if (payConfig!=null && payConfig.getXinzuan()!=null) {
            xinZuan = payConfig.getXinzuan();
        } else {
            AppConfig rechargeRate = appConfigService.getByKey("rechargeRate");
            if(rechargeRate==null) {
                throw new RRException("金额错误");
            }
            Double rate = Double.valueOf(rechargeRate.getParamValue());
            xinZuan = (int)(money*rate);
        }

        if ("alipay".equals(walletPay.getPayType())) {
            AlipayConfig alipayConfig = alipayConfigService.getAlipayAccount(money);
            if (alipayConfig == null) {
                return R.error("账户错误");
            }
        } else if ("wechat".equals(walletPay.getPayType())) {
            WechatConfig wechatAccount = wechatConfigService.getWechatAccount(walletPay.getMoney().intValue());
            if (wechatAccount == null) {
                return R.error("账户错误");
            }
        } else {
            return R.error("充值类型错误");
        }


        assertTotalPayTaday(userId);

        walletPay.setXinzuan(BigDecimal.valueOf(xinZuan));
        walletPay.setUserId(userId);
        return R.ok().put("data", walletPayService.createOrder(walletPay));
    }

    /** 支付回调 */
    @PostMapping("/notify")
    public R notify(@RequestParam Map<String, Object> params){
        walletPayService.aliNotify(params);
        return R.ok();
    }

    /** 微信支付回调 */
    @PostMapping("/wechatNotify/{configId}")
    public R wechatNotify(@RequestHeader("Wechatpay-Timestamp")String tempStemp,
                          @RequestHeader("Wechatpay-Nonce")String nonce,
                          @RequestHeader("Wechatpay-Signature")String signature,
                          @RequestBody String body,@PathVariable("configId") Integer configId) {
        Map<String, Object> heads = new HashMap<>();
        heads.put("Wechatpay-Timestamp", tempStemp);
        heads.put("Wechatpay-Nonce", nonce);
        heads.put("Wechatpay-Signature", signature);
        walletPayService.wechatNotify(heads, body, configId);
        return R.ok();
    }

    /** 苹果商品列表 */
    @GetMapping("/appleGoodsList")
    public R appleGoodsList(){
        List<String> list = applePayGoodsService.appleGoodsList();
        return R.ok(list);
    }

    /** 苹果支付结果 */
    @PostMapping("/applePayResult")
    public R applePayResult(@RequestBody String body, @RequestAttribute("userId")Integer userId){
        boolean result = walletPayService.applePayResult(body, userId);
        if (!result) {
            return R.error("支付失败");
        }
        return R.ok();
    }

    /**单日直充到达5000rmb必须实名制*/
    private void assertTotalPayTaday(Integer userId) {
        BigDecimal totalPay = walletPayService.getPayToday(userId);
        String payOneDayStr = propertyService.getV("biggest_pay_one_day");
        if (payOneDayStr!=null) {
            int payOneDay = Integer.parseInt(payOneDayStr);
            if (totalPay!=null && totalPay.intValue()>payOneDay) {
                Identify identify = identifyService.getOne(new QueryWrapper<Identify>().eq("user_id", userId));
                if (identify == null) {
                    throw new RRException("请先实名认证");
                }
            }
        }
    }
}